package com.myday.system.controller;

import com.alibaba.fastjson2.JSON;
import com.myday.system.domain.dto.MessageDTO;
import com.myday.system.domain.dto.OldToNewMessageVO;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author: xiaofengs
 * @description :
 * @date: 2024/5/20 13:52
 * @version: 1.0
 */

@RestController
@RequestMapping("/chat")
public class ChatController extends BaseController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    WebSocketServerController webSocketServerController;

    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('chatroom:manage')")
    public AjaxResult list() {
        Long size = redisTemplate.opsForList().size("chat");
        List<String> list = redisTemplate.opsForList().range("chat", 0, size);
        System.out.println(list);
        return success((Object) JSON.toJSONString(list));
    }

    @PostMapping("/send")
    @PreAuthorize("@ss.hasPermi('chatroom:manage')")
    public AjaxResult send(@RequestBody OldToNewMessageVO oldToNewMessageVO) {
        MessageDTO messageDTO = new MessageDTO();
        BeanUtils.copyProperties(oldToNewMessageVO, messageDTO);
        MessageDTO oldMessageDTO = new MessageDTO(oldToNewMessageVO.getUserId(), oldToNewMessageVO.getOldMessage());
        redisTemplate.opsForList().remove("chat",0,JSON.toJSONString(oldMessageDTO));

        webSocketServerController.sendOneUserMessage(messageDTO);
        return success();
    }
}
